<template>
  <div style="display: inline">
    <el-form-item label="工段">
      <el-select
        v-model="searchParam.workshopSectionId"
        placeholder="请选择工段"
        clearable
        filterable
        @change="changeWorkshopSection"
      >
        <el-option
          v-for="item in workshopSectionList"
          :key="item.id"
          :label="item.workshopSectionCode"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="工序">
      <el-select
        v-model="searchParam.processId"
        placeholder="请选择工序"
        clearable
        filterable
        @change="processChange"
      >
        <el-option
          v-for="item in processList"
          :key="item.id"
          :label="item.processCode"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="生产线">
      <el-select
        v-model="searchParam.equipId"
        placeholder="请选择生产线"
        clearable
        filterable
        @change="equipChange"
      >
        <el-option
          v-for="item in equipList"
          :key="item.id"
          :label="item.equipCode"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      label="型号描述"
      :required="props.requiredList.includes('productId')"
    >
      <el-select
        v-model="searchParam.productId"
        placeholder="请选择型号描述"
        clearable
        filterable
        :filter-method="customFilter1"
        @change="productChange"
      >
        <el-option
          v-for="item in filteredOptions1"
          :key="item.id"
          :label="`${item.productName}`"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      label="产品型号"
      :required="props.requiredList.includes('productId')"
    >
      <el-select
        v-model="searchParam.productId"
        placeholder="请选择产品型号"
        clearable
        filterable
        :filter-method="customFilter"
        @change="productChange"
      >
        <el-option
          v-for="item in filteredOptions"
          :key="item.id"
          :label="item.productCode"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      label="检具类别"
      v-if="props.hasGageEquipCode"
      :required="props.requiredList.includes('gageEquipCode')"
    >
      <el-select
        v-model="searchParam.gageEquipCode"
        placeholder="请选择检具类别"
        clearable
        filterable
        @change="changeEquipCode"
      >
        <el-option
          v-for="item in gageEquipList"
          :key="item.groupCode"
          :label="item.groupName"
          :value="item.groupCode"
        />
      </el-select>
    </el-form-item>
  </div>
</template>

<script setup lang="ts">
import { ElInput } from "element-plus";
import request from "@/utils/request";
import {
  getMdminspectiontoolApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getSpecificListApi,
  getMdmprocessListApi,
  getMdmProcessEquipApi1,
  getMdminspectionGroupApi,
} from "@/utils/commonData";
import _ from "lodash-es";
import { deepClone } from "@/utils/commonHooks";

defineOptions({
  name: "PCMMONITORINGCOMMONSEARCH",
  inheritAttrs: false,
});
const props = defineProps({
  data: {
    // v-model 绑定
    type: Object,
    default: () => {},
  },
  hasGageEquipCode: {
    // v-model 绑定
    type: Boolean,
    default: true,
  },
  requiredList: {
    // v-model 绑定
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits([
  "update:data",
  "changeSearch",
  "changeGageEquipCode",
]);

// 创建响应式副本
const searchParam = ref({
  processId: "",
  processCode: "",
  equipId: "",
  equipCode: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  productId: "",
  productCode: "",
  productName: "",
  workshopSectionId: "",
  workshopSectionCode: "",
  gageEquipCode: "",
  gageEquipName: "",
  gageEquipId: "",
});

// 监听父组件传入的 data 变化
watch(
  () => props.data,
  (newVal) => {
    const arr = deepClone(newVal);
    searchParam.value.processId = newVal.processId;
    searchParam.value.processCode = newVal.processCode;
    searchParam.value.equipId = newVal.equipId;
    searchParam.value.equipCode = newVal.equipCode;
    searchParam.value.productId = newVal.productId;
    searchParam.value.productCode = newVal.productCode;
    searchParam.value.productName = newVal.productName;
    searchParam.value.workshopSectionCode = newVal.workshopSectionCode;
    searchParam.value.workshopSectionId = newVal.workshopSectionId;
    searchParam.value.gageEquipCode = newVal.gageEquipCode;
    searchParam.value.gageEquipName = newVal.gageEquipName;
    searchParam.value.gageEquipId = newVal.gageEquipId;
    if (
      searchParam.value.workshopSectionId == "" &&
      searchParam.value.processId == "" &&
      searchParam.value.equipId == "" &&
      searchParam.value.productId == "" &&
      searchParam.value.gageEquipCode == ""
    ) {
      showRealCode(true, false);
    }
  },
  { deep: true }
);

// 获取实际搜索返回
const realCodes = ref<any>([]);
const getRealCode = async () => {
  return new Promise<void>((resolve, reject) => {
    request({
      url: `/dmpDosPcm/pcmmeasurefeaturesgroup/getSearchLsit`,
      method: "post",
      data: {
        processCode: searchParam.value.processCode, //工序
        equipCode: searchParam.value.equipCode, //生产线
        projectCode: searchParam.value.projectCode, //项目
        modelCode: searchParam.value.productCode, //型号
        gageEquipMarkCode: searchParam.value.gageEquipCode, //检具code
        workshopSectionCode: searchParam.value.workshopSectionCode, //工段code
      },
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

defineExpose({
  getRealCode,
  showRealCode,
  searchParam,
  getRealCodes,
});

// 统一处理变化事件
const handleChange = (field, value) => {
  // 触发 v-model 更新
  emit("update:data", { ...searchParam.value });
};

// 获取工序列表
const processList = ref<any>([]);
async function getProcessList(id: string) {
  oldProcessList.value = (await getMdmprocessListApi({})) || [];
  showRealCode(false, false);
}

async function processChange(id: string) {
  // 项目->工序->设备
  // 当 改变工序时 一定清空设备数据 重新获取设备下拉  判断是否存在项目  有的话不清空也不清空列表 没有说明一开始就选工序,没有选项目 清空项目加获取项目列表
  /*
   */
  //
  //  设备 产品型号 工序 都根据项目id重新获取下拉列表
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
  } else {
    searchParam.value.processCode = "";
  }
  showRealCode(true, id ? true : false);

  emit("changeSearch", searchParam.value);
}

// 获取产品型号列表
const productList = ref<any>([]);
const filteredOptions = ref<any>([]);
async function getProductList(params) {
  oldProductList.value = (await getMdmproductinfosApi(params)) || [];
  showRealCode(false, false);
}

// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query: any) => {
  const arr = oldProductList.value.filter((item: any) =>
    realCodes.value.modelCodes.includes(item.productCode)
  );
  if (!query) {
    filteredOptions.value = [...arr];
    return;
  }
  filteredOptions.value = arr.filter((option: any) =>
    option.productCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

const filteredOptions1 = ref<any>([]);
const customFilter1 = _.debounce((query: any) => {
  const arr = oldProductList.value.filter((item: any) =>
    realCodes.value.modelCodes.includes(item.productCode)
  );
  if (!query) {
    filteredOptions1.value = [...arr];
    return;
  }
  filteredOptions1.value = arr.filter((option: any) =>
    option.productName.toLowerCase().includes(query.toLowerCase())
  );
}, 300); // 延迟 300ms

async function productChange(id: string) {
  if (id) {
    const current: any =
      oldProductList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.productCode = current.productCode || "";
    searchParam.value.productName = current.productName || "";
  } else {
    searchParam.value.productCode = "";
    searchParam.value.productName = "";
  }
  showRealCode(true, id ? true : false);
  emit("changeSearch", searchParam.value);
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(params: Object) {
  oldEquipList.value = (await getMdmProcessEquipApi1(params)) || [];
  showRealCode(false, false);
}

async function equipChange(id: string) {
  // 项目->工序->设备
  // 当 设备改变时  获取 项目和工序的名称赋值 及项目和工序及下拉数据 并且改变自身的下拉列表
  // ------------------------------------------------------------------------------------------------------------------------ 设备后续 再写
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.equipCode = current.equipCode || "";
  } else {
    searchParam.value.equipCode = "";
  }
  showRealCode(true, id ? true : false);
  emit("changeSearch", searchParam.value);
}

let oldProcessList = ref<any>([]);
let oldEquipList = ref<any>([]);
let oldProductList = ref<any>([]);
let oldWorkshopSectionList = ref<any>([]);
let oldGageEquipList = ref<any>([]);

// 产品型号和检具都没有对应的联动关系

// 工段=》工序=》生产线 连续联动
// 存储所有的信息后，
// change之后不用前端手动联动，
// 调用后端接口进行数据过滤即可

onMounted(async () => {
  // -----------------------
  realCodes.value = await getRealCode();
  // 获取工序列表
  getProcessList({});

  // 获取设备列表
  getEquipList({});

  // 获取产品型号列表
  getProductList({});

  // 工段
  getWorkshopSectionList();

  // 检具列表
  getGageEquipList("");
});

async function getRealCodes() {
  realCodes.value = await getRealCode();
}

const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    oldWorkshopSectionList.value = res.data;
  });
};
const changeWorkshopSection = async (id) => {
  if (id) {
    const current: any =
      workshopSectionList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.workshopSectionCode = current.workshopSectionCode || "";
  } else {
    searchParam.value.workshopSectionCode = "";
  }
  showRealCode(true, id ? true : false);
  emit("changeSearch", searchParam.value);
};

// 间距变化
const changeEquipCode = (id: string) => {
  if (id) {
    const current: any =
      gageEquipList.value?.filter((e: any) => e.groupCode === id)[0] ?? {};
    searchParam.value.gageEquipName = current.groupName || "";

    emit("changeGageEquipCode", id);
  } else {
  }
  showRealCode(true, id ? true : false);
  emit("changeSearch", searchParam.value);
};

// 获取量检具列表
const gageEquipList = ref<any>([]);
async function getGageEquipList(type: string) {
  oldGageEquipList.value = (await getMdminspectionGroupApi({})) || [];
  console.log("3333", oldGageEquipList.value);

  showRealCode(false, false);
}

async function showRealCode(isApi = true, isShow = true) {
  isApi && (realCodes.value = await getRealCode());

  // 工段----------
  workshopSectionList.value =
    oldWorkshopSectionList.value.filter((item: any) =>
      realCodes.value.workshopSectionCodes.includes(item.workshopSectionCode)
    ) ?? [];

  if (isShow && realCodes.value.workshopSectionCodes.length === 1) {
    const code = realCodes.value.workshopSectionCodes[0];
    searchParam.value.workshopSectionCode = code;
    const current: any =
      oldWorkshopSectionList.value?.filter(
        (e: any) => e.workshopSectionCode === code
      )[0] ?? {};
    searchParam.value.workshopSectionId = current?.id;
  }

  // 工序----------
  processList.value =
    oldProcessList.value.filter((item: any) =>
      realCodes.value.processCodes.includes(item.processCode)
    ) ?? [];

  if (isShow && realCodes.value.processCodes.length === 1) {
    const code = realCodes.value.processCodes[0];
    searchParam.value.processCode = code;
    const current: any =
      oldProcessList.value?.filter((e: any) => e.processCode === code)[0] ?? {};
    searchParam.value.processId = current?.id;
  }

  // 生产线----------
  equipList.value =
    oldEquipList.value.filter((item: any) =>
      realCodes.value.equipCodes.includes(item.equipCode)
    ) ?? [];
  if (isShow && realCodes.value.equipCodes.length === 1) {
    const code = realCodes.value.equipCodes[0];
    searchParam.value.equipCode = code;
    const current: any =
      oldEquipList.value?.filter((e: any) => e.equipCode === code)[0] ?? {};
    searchParam.value.equipId = current?.id;
  }

  // 型号----------
  filteredOptions.value =
    oldProductList.value.filter((item: any) =>
      realCodes.value.modelCodes.includes(item.productCode)
    ) ?? [];
  filteredOptions1.value = filteredOptions.value;
  if (isShow && realCodes.value.modelCodes.length === 1) {
    const code = realCodes.value.modelCodes[0];
    searchParam.value.productCode = code;
    const current: any =
      oldProductList.value?.filter((e: any) => e.productCode === code)[0] ?? {};
    searchParam.value.productId = current?.id;
    searchParam.value.productName = current?.productName;
  }

  // 检具----------
  gageEquipList.value =
    oldGageEquipList.value?.filter((item: any) =>
      realCodes.value.toolCode.includes(item.groupCode)
    ) ?? [];
  if (isShow && realCodes.value.toolCode.length === 1) {
    const code = realCodes.value.toolCode[0];
    const current: any =
      oldGageEquipList.value?.filter((e: any) => e.groupCode === code)[0] ?? {};
    searchParam.value.gageEquipName = current?.groupName;
  }
  emit("changeSearch", searchParam.value);
}
</script>
